package com.ecgsystem.activity;

import java.util.concurrent.ConcurrentLinkedQueue;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.FrameLayout.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.ecgsystem.constants.Constants;
import com.ecgsystem.panel.OnlinePanels;
import com.ecgsystem.thread.TCPClient;
import com.ecgsystem.thread.ThreadGetSignal;
import com.ecgsystem.writelog.WriteLog;
import com.ecgsystem.R;
/**
 * TODO Put here a description of what this class does.
 * 
 * @author ANHTUAN. Created Sep 24, 2012.
 */
public class OnlineECG extends Activity implements Constants {
	private static OnlinePanels panel;
	private LinearLayout.LayoutParams panelParam;
	private ScrollView verticalView;
	private HorizontalScrollView horizotalView;
	private LinearLayout internalWrapper;
	private ThreadGetSignal threadGetSignal;
	private static Context context;
	private static Handler handler;
	
	private TCPClient mTcpClient;
	public static int patientNo;
	/**
	 * Hang doi chua tin hieu ecg
	 */
	public static ConcurrentLinkedQueue<Short> QueueDraw[];
	/**
	 * Co trang thai cho phep bat dau ve
	 */
	public static boolean startDraw = false;
	private static Thread mainLoop;
	public static boolean flag = false;// co bao hieu trang thai tin hieu san sang gui chua

	@SuppressWarnings({ "cast", "unchecked" })
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		context = this;

		// cuon doc
		this.verticalView = new ScrollView(this);
		// cuon ngang
		this.horizotalView = new HorizontalScrollView(this);

		this.panelParam = new LinearLayout.LayoutParams(
				android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		this.panelParam.height = (int) OnlinePanels.PixelPerMm * 105;
		this.panelParam.width = (int) (OnlinePanels.PixelPerMm) * 240;

		panel = new OnlinePanels(this);
		panel.setLayoutParams(this.panelParam);
		panel.clearFocus();
		panel.setEnabled(false);
		// Tao man hinh cuon ngang
		this.internalWrapper = new LinearLayout(this);
		this.internalWrapper.setLayoutParams(new LayoutParams(
				android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.FILL_PARENT));

		this.horizotalView.addView(this.internalWrapper);

		this.internalWrapper.addView(panel);
		
		this.horizotalView.setSmoothScrollingEnabled(true);
		// Tao man hinh cuon doc
		this.verticalView.addView(this.horizotalView,
				new ViewGroup.LayoutParams(
						android.view.ViewGroup.LayoutParams.FILL_PARENT,
						android.view.ViewGroup.LayoutParams.FILL_PARENT));
		this.verticalView.setSmoothScrollingEnabled(true);
		this.verticalView.setBackgroundResource(R.drawable.ecg_background);

		setContentView(this.verticalView);

		QueueDraw = (ConcurrentLinkedQueue<Short>[]) new ConcurrentLinkedQueue[12];
		for (int i = 0; i < 12; i++) {
			QueueDraw[i] = new ConcurrentLinkedQueue<Short>();
		}

		Toast.makeText(this, "An Menu de bat dau nhan", Toast.LENGTH_LONG)
				.show();
		
		handler = new Handler();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (this.threadGetSignal != null && this.threadGetSignal.isAlive()) {
			mTcpClient = new TCPClient("StopReceive|P20120001|" + patientNo);
			mTcpClient.start();
			this.threadGetSignal.stopRun();
		}
		Log.d("Events", "In onDestroy()");
	}

	@Override
	public void onPause(){
		super.onPause();
	}
	
	@Override
	public void onStop(){
		super.onStop();
		if (this.threadGetSignal != null && this.threadGetSignal.isAlive()) {
			mTcpClient = new TCPClient("StopReceive|P20120001|" + patientNo);
			mTcpClient.start();
			this.threadGetSignal.stopRun();
			//Ghi log
			new WriteLog().write();
		}
	}
	/**
	 * Ve tin hieu ECG: Lay tin hieu va ve
	 * 
	 */
	public void DrawSignal() {
		if (!startDraw) {
			startDraw = true;
			GetSignal();
			StartDraw();
		}
	}

	/**
	 * Cho tin hieu den roi ve
	 * 
	 */
	public void StartDraw() {
		mainLoop = new Thread() {
			@Override
			public void run() {
				try {
					while (!startDraw) {
						Thread.sleep(1000);
					}
					panel.setQueueDraw(QueueDraw);
					panel.StartDraw();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		};
		mainLoop.start();
	}

	/**
	 * Dung thread ve
	 * 
	 */
	public static void StopDraw() {
		startDraw = false;
		panel.Stop();
		if (mainLoop != null && mainLoop.isAlive()) {
			boolean retry = true;
			while (retry) {
				try {
					mainLoop.join();
					retry = false;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		mainLoop = null;
	}

	/**
	 * Khoi dong thread lay tin hieu realtime
	 * 
	 */
	public void GetSignal() {
		this.threadGetSignal = new ThreadGetSignal();
		this.threadGetSignal.start();
	}

	@Override
	public boolean onKeyDown(final int keyCode, final KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (this.threadGetSignal != null && this.threadGetSignal.isAlive()) {
				mTcpClient = new TCPClient("StopReceive|P20120001|" + patientNo);
				mTcpClient.start();
				this.threadGetSignal.stopRun();
			}
			//Ghi log
			new WriteLog().write();
			Intent i = new Intent(OnlineECG.this, PatientList.class);
			startActivity(i);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			OnlineECG.flag = false;
			connectTCPServer();
		}
		return true;
	}

	private void connectTCPServer(){
		mTcpClient = new TCPClient("RequestData|P20120001|");
		mTcpClient.start();
        DrawSignal();
	}
	public static Context getContext() {
		return context;
	}
	
	public static void displayAlert(final String mess){
		handler.post(new Runnable() {
            public void run() {
              Toast.makeText(context, mess, Toast.LENGTH_LONG).show();
            }
          });
	}
}
